﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.BLL.Ali;
using CRM.UTIL;
using CRM.WEB.CommonClass;

namespace CRM.WEB.Ali
{
    public partial class ImportOrder : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
            }
        }

        public void InitData()
        {
            var list = EnumBase.GetSortedList(typeof (OrderFromType));
            DLL_OrderFromType.DataSource = list;
            DLL_OrderFromType.DataTextField = "value";
            DLL_OrderFromType.DataValueField = "key";
            DLL_OrderFromType.DataBind();
        }

        //protected void btnUpLoad_Click(object sender, EventArgs e)
        //{
        //    if (fileControl.HasFile)
        //    {
        //        string folder = string.Empty;
        //        string dirPath = CommonClass.Common.GetUpLoadDirPath(Server, out folder);


        //        string fileName = fileControl.FileName;
        //        string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

        //        fileName = CommonClass.Common.GetNewFileName(dirPath, fileName);
        //        if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
        //            strFileExt.ToLower() == "xlsx")
        //        {
        //            //upload to server
        //            string serverName = Server.MapPath(folder).Trim('\\') + "\\" + fileName;
        //            fileControl.PostedFile.SaveAs(serverName);


        //            var dt = ExcelHelper.ExcelToTable(serverName);

        //            const string colOrderID = "parent_order_id";
        //            const string colsnapShotId = "snapshot_id";
        //            const string colpayOrderTime = "pay_order_time";


        //            if (!dt.Columns.Contains(colOrderID) || !dt.Columns.Contains(colsnapShotId) || !dt.Columns.Contains(colpayOrderTime))
        //            {
        //                ShowAlert("文件列不合法！不包含列：parent_order_id或snapshot_id或pay_order_time");
        //                return;
        //            }

        //            var sbFail = new StringBuilder();
        //            var existSb = new StringBuilder();

        //            var succCount = 0;
        //            var failCount = 0;
        //            var existCount = 0;
        //            var serv = new Ali_OrdersB();
        //            var aliApiServ = new RunAliAPI();
        //            var supplierId = ConfigurationManager.AppSettings["SupplierId"];
        //            for (var i = 0; i < dt.Rows.Count; i++)
        //            {
        //                try
        //                {
        //                    var dr = dt.Rows[i];

        //                    if (string.IsNullOrEmpty(dr[colOrderID].ToString().Trim()))
        //                    {
        //                        failCount++;
        //                        sbFail.Append("第" + (i + 1) + "行订单号为空！\r\n");
        //                        continue;
        //                    }
        //                    var enid = string.Empty;
        //                    var ruid = string.Empty;
        //                    try
        //                    {
        //                        var htId = JSON.Decode(dr[colsnapShotId].ToString()) as Hashtable;
        //                        if (htId != null)
        //                        {
        //                            enid = htId["en"].ToString();
        //                            ruid = htId["ru"].ToString();
        //                        }
        //                    }
        //                    catch
        //                    {
        //                    }

        //                    //根据订单号和ENid判断是否存在
        //                    var stu = new MODEL.Ali.GetAli_Orders();
        //                    stu.ORDERIDVALUE = dr[colOrderID];
        //                    stu.ENIDVALUE = enid;
        //                    var oDt = serv.GetAli_Orders(ref stu);

        //                    if (oDt == null || oDt.Rows.Count <= 0)
        //                    {

        //                        var resJson = aliApiServ.GetOrderInfo(dr[colOrderID].ToString(), false, false);

        //                        var htFirst = JSON.Decode(resJson) as Hashtable;
        //                        if (htFirst["success"].ToString().ToLower() == "true")
        //                        {
        //                            var insStu = new MODEL.Ali.EditAli_Orders();

        //                            insStu.ENIDVALUE = enid;
        //                            insStu.RUIDVALUE = ruid;

        //                            CommonClass.Common.InitDataEntity(htFirst, enid, true, ref insStu);

        //                            insStu.EFFECTIVE_VALUE = false;
        //                            insStu.ACTION_VALUE = "Insert";
        //                            insStu.EFFECTIVE_VALUE = false;

        //                            serv.EditAli_Orders(ref insStu);
        //                            succCount++;
        //                        }
        //                        else
        //                        {
        //                            failCount++;
        //                            sbFail.Append("第" + (i + 1) + "行根据订单号：" + dr[colOrderID] + "获取订单信息失败！\r\n");
        //                        }
        //                    }
        //                    else
        //                    {
        //                        existCount++;
        //                        existSb.Append((i + 1) + "、");
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    sbFail.Append("第" + (i + 1) + "行异常！" + ex.Message + "\r\n");
        //                }
        //            }

        //            //ShowAlert();

        //            txtInfo.Text = string.Format("导入成功数量：{0}！\r\n导入失败数量：{1}\r\n{2}\r\n{3}\r\n{4}", succCount, failCount,
        //                existCount != 0 ? "已存在数量:" + existCount + "" : string.Empty,
        //                string.IsNullOrEmpty(existSb.ToString())
        //                    ? string.Empty
        //                    : "第" + existSb.ToString().Trim('、') + "行数据已存在",
        //                string.IsNullOrEmpty(sbFail.ToString()) ? string.Empty : sbFail.ToString());
        //        }
        //        else
        //        {
        //            ShowAlert("请选择正确的文件类型！");
        //        }
        //    }
        //    else
        //    {
        //        ShowAlert("请选择文件！");
        //    }
        //}

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtOrderID.Text.Trim()))
            {
                ShowAlert("请输入订单号！");
            }
            else
            {
                try
                {
                    int succCount = 0;
                    int failCount = 0;
                    int updateCount = 0;
                    var sbFail = new StringBuilder();
                    var serv = new Ali_OrdersB();
                    var aliApiServ = new RunAliAPI();
                    //根据订单号和ENid判断是否存在
                    var stu = new MODEL.Ali.GetAli_Orders {ORDERIDVALUE = txtOrderID.Text.Trim()};
                    var oDt = serv.GetAli_Orders(ref stu);

                    if (oDt == null || oDt.Rows.Count <= 0)
                    {
                        //订单不存在， 新增
                        var resJson = aliApiServ.GetOrderInfo(txtOrderID.Text.Trim(), false, false);

                        var htFirst = JSON.Decode(resJson) as Hashtable;
                        if (htFirst != null && htFirst["success"].ToString().ToLower() == "true")
                        {
                            var arrayList = htFirst["dataList"] as ArrayList;
                            if (arrayList != null)
                            {
                                foreach (Hashtable item in arrayList)
                                {
                                    var insStu = new MODEL.Ali.EditAli_Orders();
                                    insStu.ORDERID_VALUE = txtOrderID.Text.Trim();
                                    insStu.ENIDVALUE = item["snapshotId"];
                                    //insStu.RUIDVALUE = ruid;
                                    insStu.BizID_VALUE = item["bizId"];

                                    CommonClass.Common.InitDataEntity(htFirst, insStu.BizID_VALUE.ToString(), true,
                                        ref insStu);

                                    insStu.EFFECTIVE_VALUE = false;
                                    insStu.ACTION_VALUE = "Insert";
                                    insStu.EFFECTIVE_VALUE = false;

                                    int i = serv.EditAli_Orders(ref insStu);
                                    if (i > 0)
                                        succCount++;
                                    else
                                    {
                                        failCount++;
                                    }
                                }
                            }
                        }
                        else
                        {
                            failCount++;
                            sbFail.Append("根据订单号：" + txtOrderID.Text.Trim() + "获取订单信息失败！Info:" + resJson + "\r\n");
                        }
                    }
                    else
                    {
                        //订单存在   同步部分信息
                        foreach (DataRow dr in oDt.Rows)
                        {
                            var entity = new MODEL.Ali.EditAli_Orders
                            {
                                ACTION_VALUE = "Update",
                                ID_VALUE = dr["ID"].ToString()
                            };

                            var resJson = aliApiServ.GetOrderInfo(dr["OrderId"].ToString(), false, false);


                            var htFirst = JSON.Decode(resJson) as Hashtable;
                            if (htFirst["success"].ToString().ToLower() == "true")
                            {

                                CommonClass.Common.InitDataEntity(htFirst, dr["BizID"].ToString(),
                                    false, ref entity);

                                int i = serv.EditAli_Orders(ref entity);
                                if (i > 0)
                                    updateCount++;
                                else
                                {
                                    failCount++;
                                }
                            }
                            else
                            {
                                sbFail.Append("调用Ali接口失败;");
                            }
                        }

                    }
                    txtInfo.Text = string.Format("导入成功数量：{0}！\r\n导入失败数量：{1}\r\n更新数量：{2}\r\n{3}", succCount, failCount,
                        updateCount,
                        string.IsNullOrEmpty(sbFail.ToString()) ? string.Empty : sbFail.ToString());
                }
                catch (Exception ex)
                {
                    txtInfo.Text = ex.Message;
                }
            }
        }

        protected void Unnamed2_Click(object sender, EventArgs e)
        {
            if (OtherOrderFile.HasFile && !string.IsNullOrEmpty(DLL_OrderFromType.SelectedValue))
            {
                if (DLL_OrderFromType.SelectedValue != ((int) OrderFromType.Aliexpress).ToString())
                {
                    string folder = string.Empty;
                    string dirPath = CommonClass.Common.GetUpLoadDirPath(Server, out folder);


                    string fileName = OtherOrderFile.FileName;
                    string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                    fileName = CommonClass.Common.GetNewFileName(dirPath, fileName);
                    if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                        strFileExt.ToLower() == "xlsx")
                    {
                        //upload to server
                        string serverName = Server.MapPath(folder).Trim('\\') + "\\" + fileName;
                        OtherOrderFile.PostedFile.SaveAs(serverName);


                        var dt = ExcelHelper.ExcelToTable(serverName);

                        const string orderNO = "Order NO";
                        const string bizId = "Biz ID";
                        const string orderDate = "Order Date";
                        const string getGoodsDate = "Get goods date";
                        const string warrantyType = "WarrantyType";
                        const string productType = "ProductType";
                        const string productAmount = "ProductAmount";
                        const string orderCurrency = "OrderCurrency";
                        const string productCount = "ProductCount";
                        const string serviceAmount = "ServiceAmount";
                        const string effective = "Effective";
                        const string effectiveDate = "EffectiveDate";
                        const string serviceStartTime = "ServiceStartTime";
                        const string serviceEndTime = "ServiceEndTime";
                        const string productSnapshotUrl = "productSnapshotUrl";
                        const string productName = "productName";
                        const string brand = "Brand";
                        const string model = "Model";
                        const string ram = "RAM";
                        const string rom = "ROM";
                        const string displaySize = "Display Size";
                        const string displayResolution = "DisplayResolution";
                        const string batteryCapacity = "BatteryCapacity";
                        const string cpu = "CPU";
                        const string color = "Color";
                        const string size = "Size";
                        const string operationSystem = "OperationSystem";
                        const string os = "OS";
                        const string productProperties = "ProductProperties";
                        const string imeiNO = "IMEI No";
                        const string snNO = "SN No";
                        const string name = "Customer name";
                        const string phone = "Telephone";
                        const string country = "Customer country";
                        const string city = "Customer city";
                        const string description = "Description for issue";
                        const string email = "Email";
                        //const string description = "Description for issue";


                        if (!dt.Columns.Contains(orderNO) ||
                            !dt.Columns.Contains(bizId) ||
                            !dt.Columns.Contains(orderDate) ||
                            !dt.Columns.Contains(getGoodsDate) ||
                            !dt.Columns.Contains(warrantyType) ||
                            !dt.Columns.Contains(productType) ||
                            !dt.Columns.Contains(productAmount) ||
                            !dt.Columns.Contains(orderCurrency) ||
                            !dt.Columns.Contains(productCount) ||
                            !dt.Columns.Contains(serviceAmount) ||
                            !dt.Columns.Contains(effective) ||
                            !dt.Columns.Contains(effectiveDate) ||
                            !dt.Columns.Contains(serviceStartTime) ||
                            !dt.Columns.Contains(serviceEndTime) ||
                            !dt.Columns.Contains(productSnapshotUrl) ||
                            !dt.Columns.Contains(productName) ||
                            !dt.Columns.Contains(brand) ||
                            !dt.Columns.Contains(model) ||
                            !dt.Columns.Contains(ram) ||
                            !dt.Columns.Contains(rom) ||
                            !dt.Columns.Contains(displaySize) ||
                            !dt.Columns.Contains(displayResolution) ||
                            !dt.Columns.Contains(batteryCapacity) ||
                            !dt.Columns.Contains(cpu) ||
                            !dt.Columns.Contains(color) ||
                            !dt.Columns.Contains(size) ||
                            !dt.Columns.Contains(operationSystem) ||
                            !dt.Columns.Contains(os) ||
                            !dt.Columns.Contains(productProperties) ||
                            !dt.Columns.Contains(imeiNO) || !dt.Columns.Contains(snNO) || !dt.Columns.Contains(name) ||
                            !dt.Columns.Contains(phone) || !dt.Columns.Contains(country) || !dt.Columns.Contains(city) ||
                            !dt.Columns.Contains(description))
                        {
                            ShowAlert("文件列不合法！");
                            return;
                        }

                        var sbFail = new StringBuilder();
                        var existSb = new StringBuilder();

                        var succCount = 0;
                        var failCount = 0;
                        var updateSuccCount = 0;
                        var updateFailCount = 0;
                        var serv = new Ali_OrdersB();
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            try
                            {
                                var dr = dt.Rows[i];

                                if (string.IsNullOrEmpty(dr[orderNO].ToString().Trim()))
                                {
                                    failCount++;
                                    sbFail.Append("第" + (i + 1) + "行订单号为空！\r\n");
                                    continue;
                                }

                                //根据订单号和ENid判断是否存在
                                var stu = new MODEL.Ali.GetAli_Orders
                                {
                                    ORDERIDVALUE = dr[orderNO],
                                    ORDERFROMTYPE_VALUE = DLL_OrderFromType.SelectedValue
                                };

                                bool effect = false;
                                bool.TryParse(dr[effective].ToString(), out effect);
                                effect = effect || dr[effective].ToString() == "1";
                                var oDt = serv.GetAli_Orders(ref stu);

                                if (oDt == null || oDt.Rows.Count <= 0)
                                {
                                    #region 新增

                                    var insStu = new MODEL.Ali.EditAli_Orders();
                                    insStu.ORDERFROMTYPE_VALUE = DLL_OrderFromType.SelectedValue;
                                    insStu.ORDERID_VALUE = dr[orderNO];
                                    insStu.BizID_VALUE = dr[bizId];
                                    insStu.ORDERDATE_VALUE = dr[orderDate];
                                    insStu.SELLERIDGETGOODSTIME_VALUE = dr[getGoodsDate];
                                    insStu.WARRANTYTYPE_VALUE = dr[warrantyType];
                                    insStu.PRODUCTTYPE_VALUE = dr[productType];
                                    insStu.PRODUCTAMOUNT_VALUE = dr[productAmount];
                                    insStu.ORDERCURRENCY_VALUE = dr[orderCurrency];
                                    insStu.PRODUCTCOUNT_VALUE = dr[productCount];
                                    insStu.SERVICEAMOUNT_VALUE = dr[serviceAmount];
                                    insStu.EFFECTIVE_VALUE = effect;
                                    insStu.EFFECTIVEDATE_VALUE = dr[effectiveDate];
                                    insStu.SERVICESTARTTIME_VALUE = dr[serviceStartTime];
                                    insStu.SERVICEENDTIME_VALUE = dr[serviceEndTime];
                                    insStu.PRODUCTSNAPSHOTURL_VALUE = dr[productSnapshotUrl];
                                    insStu.PRODUCTNAME_VALUE = dr[productName];
                                    insStu.BRANDNAMEVALUE = dr[brand];
                                    insStu.PRODUCTMODELVALUE = dr[model];
                                    insStu.RAMVALUE = dr[ram];
                                    insStu.ROMVALUE = dr[rom];
                                    insStu.DISPLAYSIZEVALUE = dr[displaySize];
                                    insStu.DISPLAYRESOLUTIONVALUE = dr[displayResolution];
                                    insStu.BATTERYCAPACITYVALUE = dr[batteryCapacity];
                                    insStu.CPUVALUE = dr[cpu];
                                    insStu.PRODUCTSKUINFO_VALUE = "{\"Display Color\":\"" + dr[color] + "\"}";
                                    insStu.SIZEVALUE = dr[size];
                                    insStu.OPERATIONSYSTEMVALUE = dr[operationSystem];
                                    insStu.OSVALUE = dr[os];
                                    insStu.PRODUCTPROPERTIES_VALUE = dr[productProperties];
                                    insStu.PRODUCTIMEI_VALUE = dr[imeiNO];
                                    insStu.PRODUCTSN_VALUE = dr[snNO];
                                    insStu.NAME_VALUE = dr[name];
                                    insStu.TELEPHONE_VALUE = dr[phone];
                                    insStu.COUNTRY_VALUE = dr[country];
                                    insStu.CITY_VALUE = dr[city];
                                    insStu.DESCRIPTION_VALUE = dr[description];
                                    insStu.EMAIL_VALUE = dr[email];
                                    insStu.WARRANTYSTATUS_VALUE = "notSubmit";

                                    insStu.ACTION_VALUE = "Insert";

                                    int res = serv.EditAli_Orders(ref insStu);
                                    if (res > 0)
                                        succCount++;
                                    else
                                    {
                                        failCount++;
                                    }

                                    #endregion
                                }
                                else
                                {
                                    //if (dr["ID"].ToString() == ((int) OrderFromType.Aliexpress).ToString())
                                    //{
                                    //    sbFail.AppendFormat("第{0}行订单在系统中存在，且与AE订单好一致。\r\n", i + 1);
                                    //}
                                    //else
                                    {
                                        #region 更新

                                        var entity = new MODEL.Ali.EditAli_Orders
                                        {
                                            ACTION_VALUE = "Update",
                                            ID_VALUE = oDt.Rows[0]["ID"].ToString(),
                                            //ORDERID_VALUE = dr[orderNO];
                                            ORDERDATE_VALUE = dr[orderDate],
                                            SELLERIDGETGOODSTIME_VALUE = dr[getGoodsDate],
                                            WARRANTYTYPE_VALUE = dr[warrantyType],
                                            PRODUCTTYPE_VALUE = dr[productType],
                                            PRODUCTAMOUNT_VALUE = dr[productAmount],
                                            ORDERCURRENCY_VALUE = dr[orderCurrency],
                                            PRODUCTCOUNT_VALUE = dr[productCount],
                                            SERVICEAMOUNT_VALUE = dr[serviceAmount],
                                            EFFECTIVE_VALUE = effect,
                                            EFFECTIVEDATE_VALUE = dr[effectiveDate],
                                            SERVICESTARTTIME_VALUE = dr[serviceStartTime],
                                            SERVICEENDTIME_VALUE = dr[serviceEndTime],
                                            PRODUCTSNAPSHOTURL_VALUE = dr[productSnapshotUrl],
                                            PRODUCTNAME_VALUE = dr[productName],
                                            BRANDNAMEVALUE = dr[brand],
                                            PRODUCTMODELVALUE = dr[model],
                                            RAMVALUE = dr[ram],
                                            ROMVALUE = dr[rom],
                                            DISPLAYSIZEVALUE = dr[displaySize],
                                            BATTERYCAPACITYVALUE = dr[batteryCapacity],
                                            DISPLAYRESOLUTIONVALUE = dr[displayResolution],
                                            CPUVALUE = dr[cpu],
                                            PRODUCTSKUINFO_VALUE = "{\"Display Color\":\"" + dr[color] + "\"}",
                                            SIZEVALUE = dr[size],
                                            OPERATIONSYSTEMVALUE = dr[operationSystem],
                                            OSVALUE = dr[os],
                                            PRODUCTPROPERTIES_VALUE = dr[productProperties],
                                            PRODUCTIMEI_VALUE = dr[imeiNO],
                                            PRODUCTSN_VALUE = dr[snNO],
                                            NAME_VALUE = dr[name],
                                            TELEPHONE_VALUE = dr[phone],
                                            COUNTRY_VALUE = dr[country],
                                            CITY_VALUE = dr[city],
                                            DESCRIPTION_VALUE = dr[description],
                                            EMAIL_VALUE = dr[email]
                                        };
                                        int res = serv.EditAli_Orders(ref entity);
                                        if (res > 0)
                                            updateSuccCount++;
                                        else
                                        {
                                            updateFailCount++;
                                        }

                                        #endregion
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                sbFail.Append("第" + (i + 1) + "行异常！" + ex.Message + "\r\n");
                            }
                        }

                        //ShowAlert();

                        txtInfo.Text = string.Format("导入成功数量：{0}\r\n导入失败数量：{1}\r\n更新成功数量:{2}\r\n更新失败数量{3}\r\n{4}",
                            succCount,
                            failCount, updateSuccCount, updateFailCount,
                            string.IsNullOrEmpty(sbFail.ToString()) ? string.Empty : sbFail.ToString());
                    }
                    else
                    {
                        ShowAlert("请选择正确的文件类型！");
                    }
                }
                else
                {
                    ShowAlert("AE订单不能导入！");
                }
            }
            else
            {
                ShowAlert("请选择文件且选择订单来源！");
            }
        }
    }
}